const $ = (gridArea)=>document.querySelector(`button[style="grid-area: ${gridArea};"]`)
const addClick = (gridArea, fn,args)=> {
    $(gridArea).addEventListener('click',fn.bind(this,args));
}

const result = document.querySelector('.result');
let proxy = new Proxy({},{
    set(target, name,value){
        result.innerText = value;
        target[name] = value;
        return true;
    }
});

proxy.equation = '0';

let isDecimalAdded = false;
let isOperatorAdded = false;
let isStarted = false;


function isOperator(character){
    return ['+','-','x','÷'].indexOf(character) > -1;
};

function append(character){
    if(proxy.equation === '0' && !isOperator(character)){
        if(character === '.'){
            proxy.equation += '' + character;
            isDecimalAdded = true;
        }else {
            proxy.equation = ''+ character;
        }
        isStarted = true;
        return 
    }
    if(!isOperator(character)){
        if(character === '.' && isDecimalAdded){
            return
        }
        if(character === '.'){
            isDecimalAdded = true;
            isOperatorAdded = true;
        }else {
            isOperatorAdded = false;

        }
        proxy.equation += ''+ character;

    }
    if(isOperator(character) && !isOperatorAdded){
        proxy.equation += ''+character;
        isDecimalAdded = false;
        isOperatorAdded = true;
    }
};
function calculate(){
    let res = proxy.equation.replace(new RegExp('x','g'),'*').replace(new RegExp('÷','g'), '/');
    proxy.equation = parseFloat(eval(res).toFixed(9).toString());
    isDecimalAdded = false;
    isOperatorAdded = false;
}
// = 
addClick('equal',calculate);

// +/-
addClick('plus-minus',function calculateToggle(){
    if(isOperatorAdded || isStarted){
        return
    }
    proxy.equation = proxy.equation + '* -1';
    calculate();
})

// %
addClick('percent',function calculatePercenteage(){
    if(isOperatorAdded || isStarted){
        return
    }
    proxy.equation += '* 0.01';
    calculate();
});

// ac
addClick('ac',function clear(){
    proxy.equation = '0';
    isDecimalAdded = false;
    isDeperatorAdded = false;
    isStarted = false;
});

addClick('add',append,'+');
addClick('subtract',append,'-');
addClick('multiply',append,'x');
addClick('divide',append,'÷');
addClick('number-1',append,'1');
addClick('number-2',append,'2');
addClick('number-3',append,'3');
addClick('number-4',append,'4');
addClick('number-5',append,'5');
addClick('number-6',append,'6');
addClick('number-7',append,'7');
addClick('number-8',append,'8');
addClick('number-9',append,'9');
addClick('number-0',append,'0');
addClick('dot',append,'.');




